<?php

final class Loader {

    /**
     * @var array
     */
    private static $loaded = array();

    public static function includeFile($fileType, $fileName) {
        $fileType = strtolower($fileType);
        $loaded = & self::$loaded;
        if (!isset($loaded[$fileType][$fileName])) {
            if (in_array($fileType, array('app', 'config', 'helper', 'model', 'vendor', 'view', 'controller'))) {
                $loaded[$fileType][$fileName] = true;
                $s = $fileType == 'app' ? '' : 's';
                require(XF_PATH . $fileType . $s . DIRECTORY_SEPARATOR . $fileName . '.php');
            }
        }
    }

    public static function loadController($controllerName) {
        if (substr($controllerName, -10) != 'Controller') {
            $modelName = Inflector::getInstance()->singularize($controllerName);
            $controllerName .= 'Controller';
        } else {
            $modelName = Inflector::getInstance()->singularize(substr($controllerName, 0, -10));
        }
        self::includeFile('controller', $controllerName);
        $Controller = new $controllerName();

        if (isset($Controller->modelName)) {
            if ($Controller->modelName != '_') {
                $modelName = $Controller->modelName;
            }

            $modelName = self::loadModel($modelName);
            $Controller->Model = new $modelName();
        }
        
        $Controller->Layout = Layout::getInstance();
        
        if (method_exists($Controller, 'onLoad')) {
            $Controller->onLoad();
        }
        
        return $Controller;
    }

    public static function loadModel($modelName) {
        if (substr($modelName, -5) != 'Model') {
            $modelName .= 'Model';
        }
        Loader::includeFile('model', $modelName);
        return $modelName;
    }

}

?>